import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { MessageService, TreeNode } from 'primeng/api';
import { CreateOrEditBopTreeModalComponent } from '@app/admin/bop/create-or-edit-boptree-modal.component';
import { OrganizationUnitsTreeComponent } from '@app/admin/shared/organization-unit-tree.component';
import {
    WorkStepAndProcessDto, ProcessesEntityDto, BopContentEditDto,
    BopUnifyServiceProxy, BopContentServiceProxy, BopNodeServiceProxy,
    PQualitWorkStepDto, QualityPlatformServiceProxy, RbopContentInfoDto,
    RprocessesDto, RTechFileHeaderDto, OperationHistoryServiceProxy
} from '@shared/service-proxies/service-proxies';
import { Paginator } from 'primeng/components/paginator/paginator';
import * as moment from 'moment';

@Component({
    selector: 'app-file-manage-detail',
    templateUrl: './file-manage-detail.component.html',
    styleUrls: ['./file-manage-detail.component.less']
})
export class FileManageDetailComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('organizationUnitTree') organizationUnitTree: OrganizationUnitsTreeComponent;
    @ViewChild('paginator') paginator: Paginator;
    saving = false;
    treeForm = {};
    advancedFiltersAreShown = false;
    loading: boolean;
    loadingtree: boolean;
    isReceived = true;
    isCompleted = false;
    anyncing = false;
    filterText = '';
    files2: any;//树形结构
    selectedFiles: TreeNode;
    ischeckTree: any;//当前点击节点
    bopContent: BopContentEditDto = new BopContentEditDto();
    // btInfo: RbopContentInfanyoDto = new RbopContentInfoDto();//部套
    btInfo: any;//部套
    btInfoDate = undefined;// 部套新增时间
    btInfoNewDate = undefined;// 部套新增时间
    processFile: RTechFileHeaderDto = new RTechFileHeaderDto();//工艺规程
    workStepData: [];//工步动态表List
    workStepHeader: any;//工步动态表Header
    //数据导出需要的参数
    exportData: any;
    // ischangekey:0;//右侧tab切换 0为部套 1为工艺规程
    //右侧工序信息
    processInfo: ProcessesEntityDto = new ProcessesEntityDto();
    //右侧工步信息
    workstepInfo: WorkStepAndProcessDto = new WorkStepAndProcessDto();
    check = [];
    tableData = [];
    constructor(injector: Injector,
        private _bopUnifyServiceProxy: BopUnifyServiceProxy,
        private _qualityPlatformServiceProxy: QualityPlatformServiceProxy,
        private _bopNodeServiceProxy: BopNodeServiceProxy,
        private _bopContentServiceProxy: BopContentServiceProxy,
        private _operationHistoryService: OperationHistoryServiceProxy
    ) {
        super(injector);
    }
    //父组件传参
    @ViewChild('createOrEditBopTreeModal') createOrEditBopTreeModal: CreateOrEditBopTreeModalComponent;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() parentInfo: any;//父级节点信息  
    active = false;
    getUser(item) {
        let msg = item ? item.split('，') : [];
        // let result = [];
        // for (const i of msg) {
        //     let data = i.split('_');
        //     result.push(data);
        // }
        let rs = [];
        for (const item of msg) {
            let msg = item.split('*');
            let data = { name: undefined, time: undefined, url: undefined };
            data.name = msg[0];
            data.time = msg[1];
            data.url = msg[2];
            rs.push(data);
        }
        return rs;
    }
    getRefuse() {
        this._operationHistoryService.getTechOperationLogList(this.parentInfo.id, 1)
        .pipe(finalize(() => { }))
        .subscribe(result => {
            this.tableData = result;
        })
    }
    //获取树结构
    getTreeInfo(): void {
        this.loadingtree = true;
        this._bopUnifyServiceProxy.getBindWorkStepByNumber(this.parentInfo.id)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                //建立父级节点
                this.files2 = [{ techniqueName: this.parentInfo.techniqueName, techniqueNumber: this.parentInfo.techniqueNumber, id: this.parentInfo.id, key: -1, nodeDrawingNo: this.parentInfo.drawingNo, nodeName: this.parentInfo.modelName, model: this.parentInfo.model, lotNo: this.parentInfo.lotNo, stageSign: this.parentInfo.stageSign, children: result ? result : [] }];
                this.expandAll();
                this.ischeckTree = {};
                this.loadingtree = false;
            });
        this._bopUnifyServiceProxy.getTechFileHeader(this.parentInfo.id)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.processFile = result;
            });
    }
    //点击树节点
    nodeSelect(event): void {
        this.ischeckTree = event.node;
        
        //如果未关联 则差右侧
        if (parseInt(this.ischeckTree.nodeLevel) != 8 && parseInt(this.ischeckTree.nodeLevel) != 9) {
            this._bopUnifyServiceProxy.getBopUnifyInfoByNumber(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.btInfo = result;
                    this.btInfoDate = moment(result.relationDate).format('YYYY-MM-DD HH:mm:ss');
                    this.btInfoNewDate = moment(result.exportDate).format('YYYY-MM-DD HH:mm:ss');
                    var tarDiv = document.getElementById("pane1");
                    if (tarDiv.hasChildNodes()) {
                        while (tarDiv.hasChildNodes()) {
                            tarDiv.removeChild(tarDiv.firstChild);
                        }
                    }
                    var newDiv = document.createElement("div");
                    newDiv.innerHTML = this.btInfo.techniqueExplain;
                    tarDiv.appendChild(newDiv);
                });
        }
        //工序查看右侧
        if (parseInt(this.ischeckTree.nodeLevel) == 8) {
            this.check = [];
            // abp.ui.setBusy(undefined, '', 1);
            this._bopNodeServiceProxy.getProcessesById(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.processInfo = result;
                    let item = this.processInfo.processesCharacteristic.split('|');
                    this.check = item;
                    this.check.splice(this.check.length - 1, 1);
                    // abp.ui.clearBusy();
                });
        }
        //工步查看右侧
        if (parseInt(this.ischeckTree.nodeLevel) == 9) {
            // abp.ui.setBusy(undefined, '', 1);
            this._bopNodeServiceProxy.getWorkStepOut(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.workstepInfo = result;
                    // abp.ui.clearBusy();
                    this.onTabChange({ index: 0 });
                });
        }

    }

    //处理图片
    getImage(item) {
        let imageList = item ? item.split(',') : []
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
            } else {
                let a = e.split('_');
                a[a.length - 1] = a[a.length - 1].replace('thumbnail', '');
                let rs = a.join('');
                result.push({
                    source: rs,
                    thumbnail: rs,
                    title: ''
                })
            }
        })
        return result
    }
    getVideo(item) {
        let imageList = item ? item.split(',') : []
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
                result.push({
                    source: e,
                    thumbnail: e,
                    title: ''
                })
            }
        })
        return result
    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current);
            }
        }
        return result;
    }

    show(): void {
        this.active = true;
        this.modal.show();
    }

    expandAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }

    collapseAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, false);
        });
    }

    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    close(): void {
        this.active = false;
        this.files2 = [];
        this.btInfo = new RbopContentInfoDto();
        this.btInfoDate = undefined;
        this.btInfoNewDate = undefined;
        this.modal.hide();
    }
    //tab 切换工步动态表
    onTabChange(event) {
        this.workStepHeader = this.workstepInfo.tableNameDictionary[event.index];
        this.workStepData = this.workstepInfo.workStepOut[this.workstepInfo.tableNameDictionary[event.index].tablekey];
    }
    //打开弹窗
    onShown(): void {
        this.getRefuse();
    }
    ngOnInit() {
    }
}
